﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using PushEmail.Mime;
using PushEmail.Common.Logging;
using System.Linq;
using PushEmail.ViewModel;


namespace PushEmail.Common
{
    public class PEUtility
    {
        static public FolderType getFolderTypeByIndex(int index)
        {
            FolderType folderType = FolderType.invalideBoxType;
            switch (index)
            {
                case 0:
                    folderType = FolderType.inBoxType;
                    break;
                case 1:
                    folderType = FolderType.outBoxType; ;
                    break;
                case 2:
                    folderType = FolderType.draftBoxType;
                    break;
                case 3:
                    folderType = FolderType.sentBoxType;
                    break;
                default:
                    break;
            }
            return folderType;
        }

        static public uint GetFolderIdByIndex(int index, uint accountId)
        {
            FolderType folderType = getFolderTypeByIndex(index);
            PEDBManager db = PEDBManager.Instance();
            return db.peDataModel.GetSystemFolderIdByType(accountId, folderType);
        }

        static public uint GetFolderIdByIndex(int index, uint accountId, out FolderType folderType)
        {
            folderType = getFolderTypeByIndex(index);

            PEDBManager db = PEDBManager.Instance();
            return db.peDataModel.GetSystemFolderIdByType(accountId, folderType);
        }

        static public string GetAttachmentIcon(string AttachmentName, AttachmentOutOfDateStatus OutOfDateStatus)
        {
            string icon = null;

            if (!string.IsNullOrEmpty(AttachmentName))
            {
                string extension = getFileExtension(AttachmentName);

                if ((new string[] { "doc", "docx", "rtf", "docm", "dotx", "dotm" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-doc";
                }
                else if ((new string[] {
                "bmp", "gif", "jp2", "jpeg", "jpg", 
                "pcx", "png", "psd", "ras", "raw", 
                "rab", "sgi", "tga", "tif", "tiff", 
                "wbmp"}).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-picture";
                }
                else if ((new string[] { 
                    "htm", "html", "shtml", "stm", "shtm", 
                    "asp", "jsp", "php", "cgi", "xml" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-html";
                }
                else if (extension.ToUpper() == "PDF")
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-pdf";
                }
                else if (extension.ToUpper() == "TXT")
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-txt";
                }
                else if ((new string[] {
                    "3g2", "3gp", "3gp2", "3gpp", "amv",
                    "asf", "asm", "avi", "bik", "csf",
                    "d2v", "divx", "dsm", "dsv", "flc",
                    "fli", "flic", "flv", "ivf", "m1v",
                    "m2p", "m2ts", "m2v", "m4b", "m4p", 
                    "m4v", "mkv", "mov", "mp4", "mpe", 
                    "mpeg", "mpg", "mts", "ogm", "pmp",
                    "pmp2", "pss", "pva", "qt", "ram", 
                    "rm", "rmvb", "rp", "rpm", "rt", 
                    "scm", "smk", "swf", "tp", "tpr",
                    "ts", "vg2", "vid", "vob", "vp6",
                    "vp7", "webm", "wm", "wmp", "wmv", "wv" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-video";
                }
                else if ((new string[] { 
                    "mp3", "mp2", "mp1", "aac", "m4a", 
                    "wav", "wma", "amr" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-audio";
                }
                else if ((new string[] { "ppt", "pptx", "pps", "pot", "pptm", "potx", "potm" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-ppt";
                }
                else if ((new string[]{
                "zip", "rar", "7z", "cab", "img", 
                "iso", "lha", "lzh", "tar" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-zip";
                }
                else if ((new string[] { "xls", "xlsx", "xlw", "xlt", "xlsm", "xlts", "xltm", "xlsb" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-xls";
                }
                //类型补充
                else if ((new string[] { 
                    "odt", "ott", "oth", "odm", "sxw", 
                    "stw", "sxg", "ods", "ots", "sxc", 
                    "stc", "odp", "odg", "otp", "sxi", 
                    "sti" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-OpenOffice";
                }
                else if ((new string[] { "wps", "wpt", "et", "ett", "dps", "dpt" }).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-wps";
                }
                else if ((new string[]{
                    "123", "602", "cgm", "csv", "dbf", 
                    "dif", "hwp", "jtd", "jtt", "mmap",
                    "mml","mmp", "mpt", "one", "odf",
                    "pdb", "pxl", "sda", "sdc", "sdd",
                    "sdp", "sdw", "sgl", "slk", "smf", 
                    "uof", "uof", "uof", "uop",  "uos", 
                    "uot", "vor", "vor", "vsd", "wb2", 
                    "wk1", "wks", "wpd", "xps"}).Contains(extension.ToLower()))
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-other-documents";
                }
                else
                {
                    icon = "../../Images/attachmentManagement/icons/50X50-unknown";
                }

                if (!string.IsNullOrEmpty(icon))
                {
                    if (OutOfDateStatus == AttachmentOutOfDateStatus.OutOfDate)
                    {
                        icon += "-bw.png";
                    }
                    else
                    {
                        icon += ".png";
                    }
                }

            }

            return icon;
        }

        private static string getFileExtension(string attachName)
        {
            string fileName = attachName;
            if (fileName == null)
                return "";
            int extensionIndex = fileName.LastIndexOf(".");
            if (extensionIndex < 0)
                return "";
            extensionIndex++;
            if (extensionIndex >= fileName.Length)
                return "";
            return fileName.Substring(extensionIndex);

        }

        static public AttachmentOutOfDateStatus GetOutOfDateStatus(DateTime date)
        {

            DateTime now = DateTime.Now;

            if (DateTime.Compare(date.AddDays(3), now) < 0)
            {
                return AttachmentOutOfDateStatus.OutOfDate;
            }
            else if (DateTime.Compare(date.AddDays(2), now) < 0)
            {
                return AttachmentOutOfDateStatus.WillOutOfDate;
            }
            else
            {
                return AttachmentOutOfDateStatus.Nomal;
            }
        }

        public static ItemTimeSpans ResolveEmailTimeSpan(DateTime receiveTime)
        {
            DateTime now = DateTime.Now;
            DateTime itemTime = receiveTime;
            itemTime = new DateTime(itemTime.Year, itemTime.Month, itemTime.Day);
            now = new DateTime(now.Year, now.Month, now.Day);
            TimeSpan diff = now - itemTime;


            DayOfWeek dayOfWeek = now.DayOfWeek;


            switch (diff.Days)
            {
                case 0:
                    return ItemTimeSpans.TimeSpanToday;
                case 1:
                    if (dayOfWeek == DayOfWeek.Sunday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanYesterday;
                case 2:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanTheDayBeforeYesterday;
                case 3:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanThisWeek;
                case 4:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanThisWeek;
                case 5:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanThisWeek;
                case 6:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday || dayOfWeek == DayOfWeek.Friday)
                        return ItemTimeSpans.TimeSpanLastWeek;
                    else
                        return ItemTimeSpans.TimeSpanThisWeek;
                case 7:
                    return ItemTimeSpans.TimeSpanLastWeek;
                case 8:
                    if (dayOfWeek == DayOfWeek.Sunday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                case 9:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                case 10:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                case 11:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                case 12:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                case 13:
                    if (dayOfWeek == DayOfWeek.Sunday || dayOfWeek == DayOfWeek.Monday || dayOfWeek == DayOfWeek.Tuesday ||
                        dayOfWeek == DayOfWeek.Wednesday || dayOfWeek == DayOfWeek.Thursday || dayOfWeek == DayOfWeek.Friday)
                        return ItemTimeSpans.TimeSpanAncient;
                    else
                        return ItemTimeSpans.TimeSpanLastWeek;
                default:
                    return ItemTimeSpans.TimeSpanAncient;
            }
        }


        public static string getNoHTMLString(String htmlStr)
        {
            if (null == htmlStr)
                return "";
            try
            {
                string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
                string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
                string regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

                // 过滤script标签
                htmlStr = Regex.Replace(htmlStr, regEx_script, "", RegexOptions.IgnoreCase);

                // 过滤style标签
                htmlStr = Regex.Replace(htmlStr, regEx_style, "", RegexOptions.IgnoreCase);

                Regex reg_html = new Regex(regEx_html);
                htmlStr = reg_html.Replace(htmlStr, ""); // 过滤html标签

                htmlStr = htmlStr.Replace("&nbsp;", "\r\n");

                return htmlStr.Trim();
            }
            catch (Exception e)
            {
                string err = e.ToString();
                return "";
            }
        }

        static public void convertMessagePartToEmail(string emaiUID, MessageHeader headers, MessagePart messagePart, out Email email)
        {
            string mailContent = null;
            string fileExtName = ".";
            email = null;
            if (messagePart.IsMultiPart == true)
            {
                DefaultLogger.Log.LogDebug("****** multi-part mail\r\n");

                foreach (MessagePart msgPart in messagePart.MessageParts)
                {
                    if (msgPart.IsText == true)
                    {
                        if (msgPart.IsTextPlain == true)
                            fileExtName += "txt";
                        else
                            fileExtName += "html";
                        mailContent = Encoding.UTF8.GetString(msgPart.Body, 0, msgPart.Body.Length);
                        break;
                    }
                }
            }
            else if (messagePart.IsText == true)
            {
                if (messagePart.IsTextPlain == true)
                    fileExtName += "txt";
                else
                    fileExtName += "html";

                DefaultLogger.Log.LogDebug("****** text mail\r\n");
                mailContent = Encoding.UTF8.GetString(messagePart.Body, 0, messagePart.Body.Length);
            }

            if (mailContent == null)
                throw (new Exception("convert: bad content"));

            PeDataModel peDataModel = PEDBManager.Instance().peDataModel;


            uint accountId = GetAccountIdByMailBelongString(headers.MailAccount);
            if (accountId != ConstDefine.INVALID_ID)
            {
                email = new Email();
                email.accountId = accountId;
                FolderType folderType = GetMailBoxType(headers.From, headers.Subject);
                email.folderId = peDataModel.GetSystemFolderIdByType(accountId, folderType);
                email.fromAddress = headers.From;
                email.toAddress += headers.To;

                email.ccAddresses += headers.Cc;
                email.bccAddresses += headers.Bcc;
                // if (headers.ReplyTo != null)
                //     newMessage.ReplyTo = headers.ReplyTo.Address;

                email.subject = headers.Subject;
                email.mimeDate = Convert.ToDateTime(headers.Date).ToString("yyyy-MM-dd HH:mm:ss");
                email.mailUID = emaiUID;
                email.attachmentCount = 0;
                email.isHtml = messagePart.MessageParts[0].IsHtml ? 1 : 0;
                email.bodyFile = emaiUID + fileExtName;
                email.mailContent = mailContent;
                if (messagePart.IsMultiPart == true)
                {
                    foreach (MessagePart msgPart in messagePart.MessageParts)
                    {
                        if (msgPart.IsAttachment == true)
                        {
                            email.attachmentCount++;
                        }
                    }
                }
            }
            else
                throw (new Exception("convert: bad account"));
        }

        static uint GetAccountIdByMailBelongString(string mailbelong)
        {

            Account account = null;
            try
            {
                if ((mailbelong == null) || (mailbelong == ""))
                {
                    account = PEDBManager.Instance().peDataModel.Get139Account();
                }
                else
                {
                    string strAddress = RfcMailAddress.ParseMailAddress(mailbelong).Address;
                    //string.Compare(str1, str2, true);
                    account = PEDBManager.Instance().peDataModel.GetAccountByAddress(strAddress);
                }
            }
            catch (Exception e)
            {
                DefaultLogger.Log.LogDebug("GetEmailAccountId");

            }
            if (account != null)
                return account.accountId;
            return ConstDefine.INVALID_ID;
        }

        static private FolderType GetMailBoxType(string from, string subject)
        {
            FolderType ret = FolderType.inBoxType;
            string[] addrArray = { "account@139.com",
                                    "fj10086@139.com",
                                    "hbmc10086@139.com", 
                                    "hnmcc.com@139.com"};
            string[] subArr = {"电子账单",
                                "话费账单",
                                "话费清单",
                                "客户账单",
                                "E-mail帐单"};
            if ((from == null) || (from == "") || (subject == null) || (subject == ""))
                return ret;
            int index = -1;
            foreach (string substr in subArr)
            {
                index = subject.IndexOf(substr, StringComparison.OrdinalIgnoreCase);
                if (index >= 0)
                    break;
            }
            if (index >= 0)
            {
                string strAddress = RfcMailAddress.ParseMailAddress(from).Address;
                if ((strAddress == null) || (strAddress == ""))
                    return ret;
                if (strAddress.ToLower().EndsWith("chinamobile.com"))
                    ret = FolderType.billingBoxType;
                else
                {
                    foreach (string addr in addrArray)
                    {
                        if (0 == string.Compare(strAddress, addr, StringComparison.OrdinalIgnoreCase))
                        {
                            ret = FolderType.billingBoxType;
                            break;
                        }
                    }
                }
            }
            return ret;
        }

        static public bool canConvert(string attachmentName, out string type, ref bool blist)
        {
            string fileExt = Path.GetExtension(attachmentName);
            blist = false;
            type = "";
            string[] extArray = {".doc",".docx",
                                    ".xls",".xlsx",
                                    ".ppt",".pptx",
                                    ".rtf",
                                    ".pdf"
                                };
            string[] extDownArray = {".txt",
                                    ".xml",
                                    ".htm",
                                    ".html",
                                    ".mht"
                                  };

            string[] picArray = {".bmp",
                                    ".jpeg",
                                    ".jpg",
                                    ".pcx",
                                    ".tif",
                                    ".tiff",
                                    ".png",
                                    ".gif"
                                };


            foreach (string ext in extArray)
            {
                if (0 == string.Compare(fileExt, ext, StringComparison.OrdinalIgnoreCase))
                {
                    type = "+jpg"; //文件转换下载
                    blist = true;
                    return true;
                }
            }

            foreach (string ext in picArray)
            {
                if (0 == string.Compare(fileExt, ext, StringComparison.OrdinalIgnoreCase))
                {
                    type = "-jpg"; //图片压缩下载
                    return true;
                }
            }

            foreach (string ext in extDownArray)
            {
                if (0 == string.Compare(fileExt, ext, StringComparison.OrdinalIgnoreCase))
                {
                    type = ""; //文本文件、html直接下载
                    return false;
                }
            }
            return false;
            // string[] s2;

            //s2 = s1.Split(Environment.NewLine);
        }

        static public void ResetSystem()
        {
            try
            {
                PushEmail.Storage.IsolatedStorageSettingUtil.Clear();
                PEDBManager.Instance().peDataModel.DeleteDataBase(); //避免数据库删除失败
                PushEmail.Storage.IsolateStorageUtil.RemoveStorage();
            }
            catch (Exception e) //屏蔽文件操作错误
            {
                DefaultLogger.Log.LogDebug(e.ToString());
            }
        }

    }
}
